package com.ld.security.auth.common.wrapper.po;

import com.ld.security.auth.common.base.constants.JwtUserConstant;
import com.ld.security.auth.common.base.entity.JwtUserInfo;
import com.ld.security.auth.common.util.AuthUtil;
import com.ld.security.common.core.base.po.QueryPo;
import com.ld.security.common.core.base.po.SuperPo;
import com.ld.security.common.core.util.ReflectionUtil;
import com.ld.security.common.mybatis.core.entity.SqlDeptEntity;
import com.ld.security.common.mybatis.core.entity.SqlEntity;
import com.ld.security.common.mybatis.core.entity.SqlUserEntity;
import com.ld.security.common.mybatis.core.wrapper.EntityWrapper;
import com.ld.security.common.mybatis.wrapper.SimpWrapperFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class AuthWrapper extends SimpWrapperFactory {



    public <V> EntityWrapper<V> getWrapper(SuperPo po) {

        EntityWrapper ew = new EntityWrapper<>();

        SuperPo q=po;
        SimpScopePo scopePo = new SimpScopePo();

        if(po instanceof QueryPo){
            QueryPo<SuperPo> queryPo = (QueryPo)po;
            q=queryPo.getQuery();
        }



        if(q instanceof SqlEntity){
            JwtUserInfo jwtUserInfo = (JwtUserInfo) AuthUtil.getUserInfo();

            if(jwtUserInfo.getUser().getUserType() == JwtUserConstant.userType.user){
                if(q instanceof SqlUserEntity){
                    scopePo.setCrtUser(Arrays.asList(jwtUserInfo.getUser().getId()));
                }
                if(q instanceof SqlDeptEntity){
                    scopePo.setCrtDept(Arrays.asList(jwtUserInfo.getUser().getCrtDept()));
                }
            }


        }




        if(!ReflectionUtil.isNull(q)){
            scopePo.setQuery(q);
            q=scopePo;
        }
        if(q != null){
            ew.initWhere(q);
        }

        this.orderBy(ew,po);



        return ew;

    }
}
